// 网站生成器工具函数
(function(window) {
  // DOM操作辅助函数
  const $ = function(selector, context = document) {
    return context.querySelector(selector);
  };
  
  const $$ = function(selector, context = document) {
    return Array.from(context.querySelectorAll(selector));
  };
  
  // 事件绑定辅助函数
  const on = function(element, event, handler) {
    element.addEventListener(event, handler, false);
  };
  
  const off = function(element, event, handler) {
    element.removeEventListener(event, handler, false);
  };
  
  // 防抖函数
  const debounce = function(fn, delay = 300) {
    let timer = null;
    return function(...args) {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(this, args);
      }, delay);
    };
  };
  
  // 节流函数
  const throttle = function(fn, delay = 300) {
    let lastTime = 0;
    return function(...args) {
      const now = Date.now();
      if (now - lastTime >= delay) {
        fn.apply(this, args);
        lastTime = now;
      }
    };
  };
  
  // 表单验证
  const validateForm = function(form) {
    const inputs = $$('input, select, textarea', form);
    let isValid = true;
    
    inputs.forEach(input => {
      if (input.required && !input.value.trim()) {
        showError(input, '此字段为必填项');
        isValid = false;
      } else {
        hideError(input);
      }
    });
    
    return isValid;
  };
  
  // 显示错误信息
  const showError = function(element, message) {
    let errorElement = $(`.error-message[data-for="${element.id}"]`);
    
    if (!errorElement) {
      errorElement = document.createElement('div');
      errorElement.className = 'error-message text-danger mt-1 small';
      errorElement.setAttribute('data-for', element.id);
      element.parentNode.appendChild(errorElement);
    }
    
    errorElement.textContent = message;
    element.classList.add('is-invalid');
  };
  
  // 隐藏错误信息
  const hideError = function(element) {
    const errorElement = $(`.error-message[data-for="${element.id}"]`);
    if (errorElement) {
      errorElement.remove();
    }
    element.classList.remove('is-invalid');
  };
  
  // 发送AJAX请求
  const ajax = function(options) {
    const { url, method = 'GET', data = {}, success, error, complete } = options;
    
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      
      xhr.open(method, url, true);
      xhr.setRequestHeader('Content-Type', 'application/json');
      
      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          const response = JSON.parse(xhr.responseText);
          success && success(response);
          resolve(response);
        } else {
          const response = xhr.responseText ? JSON.parse(xhr.responseText) : { message: '请求失败' };
          error && error(response);
          reject(response);
        }
        complete && complete(xhr);
      };
      
      xhr.onerror = function() {
        const response = { message: '网络错误' };
        error && error(response);
        reject(response);
        complete && complete(xhr);
      };
      
      xhr.send(JSON.stringify(data));
    });
  };
  
  // 显示加载提示
  const showLoading = function(element) {
    const loading = document.createElement('div');
    loading.className = 'loading-overlay position-absolute inset-0 bg-white bg-opacity-80 flex items-center justify-center z-10';
    loading.innerHTML = `
      <div class="text-center">
        <div class="spinner-border text-primary" role="status">
          <span class="sr-only">Loading...</span>
        </div>
        <p class="mt-2 text-primary">加载中...</p>
      </div>
    `;
    
    if (element.style.position === 'static' || !element.style.position) {
      element.style.position = 'relative';
    }
    
    element.appendChild(loading);
    return loading;
  };
  
  // 隐藏加载提示
  const hideLoading = function(loadingElement) {
    if (loadingElement && loadingElement.parentNode) {
      loadingElement.parentNode.removeChild(loadingElement);
    }
  };
  
  // 显示消息提示
  const showMessage = function(type, message, duration = 3000) {
    const messageTypes = {
      success: 'alert-success',
      error: 'alert-danger',
      warning: 'alert-warning',
      info: 'alert-info'
    };
    
    const alert = document.createElement('div');
    alert.className = `alert ${messageTypes[type] || 'alert-info'} position-fixed top-5 right-5 z-50 shadow-lg px-4 py-3`;
    alert.innerHTML = `
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
      ${message}
    `;
    
    document.body.appendChild(alert);
    
    // 添加淡入动画
    setTimeout(() => {
      alert.style.transition = 'opacity 0.3s ease-in-out';
      alert.style.opacity = '1';
    }, 10);
    
    // 点击关闭按钮
    on($('.close', alert), 'click', () => {
      alert.remove();
    });
    
    // 自动关闭
    if (duration > 0) {
      setTimeout(() => {
        alert.style.opacity = '0';
        setTimeout(() => {
          alert.remove();
        }, 300);
      }, duration);
    }
    
    return alert;
  };
  
  // 格式化日期
  const formatDate = function(date, format = 'YYYY-MM-DD HH:mm:ss') {
    if (typeof date === 'string') {
      date = new Date(date);
    }
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return format
      .replace('YYYY', year)
      .replace('MM', month)
      .replace('DD', day)
      .replace('HH', hours)
      .replace('mm', minutes)
      .replace('ss', seconds);
  };
  
  // 深拷贝对象
  const deepClone = function(obj) {
    if (obj === null || typeof obj !== 'object') return obj;
    if (obj instanceof Date) return new Date(obj.getTime());
    if (obj instanceof Array) return obj.map(item => deepClone(item));
    if (typeof obj === 'object') {
      const clonedObj = {};
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          clonedObj[key] = deepClone(obj[key]);
        }
      }
      return clonedObj;
    }
  };
  
  // 导出工具函数
  window.websiteUtils = {
    $,
    $$,
    on,
    off,
    debounce,
    throttle,
    validateForm,
    showError,
    hideError,
    ajax,
    showLoading,
    hideLoading,
    showMessage,
    formatDate,
    deepClone
  };
})(window);